import {Router} from 'express'
const qs = require('querystring');
const config = require('../config.json');
const apiUrl = config.apiUrl;
const router = Router();
import axios from '../src/plugins/axios';

//微信登录
const wxLogin = function (req, res, next) {

    let originalUrl = req.originalUrl;
    //let token = req.query.token || 't6hMS8Wi+RRxXAZM69PZZqkJ0b5zk/tLnp+o1+8Us4Vu7b/s/O/73HS3My7+BFT4DGsS9Eb0bs+0k0xbjGaU0sra6hl8Y6Q7oqeNIXW60gg=..d003a31549c593c6748a5b1c95d74d38';
    let token = req.query.token || req.session.token;

    if (token) {
        req.session.token = token;
        axios.get(`/api/h5/token/userinfo`, {
            params: {
                token
            }
        }).then(rs => {
            if(rs.data.error === 0){
                Object.assign(res.locals, {userInfo: rs.data.data, token});
                next()
            }else {
                res.redirect(`/error?message=${rs.data.desc}`)
            }
        }).catch(e => {
            res.redirect(`/error?message=网络错误`)
        });

    } else {
        let callbackUrl = qs.escape(`${config.callBackUrl}${originalUrl}`);
        //let callbackUrl = qs.escape(`http://192.168.1.102:3000${originalUrl}`);
        res.redirect(`http://wx-auth.yidikala.com/wechat-mobile-auth/?callback_url=${callbackUrl}`)
    }
};

// get 获取参数
const getParams = function (req) {
    return {
        store_id: req.query.store,
        table_id: req.query.table,
        num: req.query.num
    }
};

// 判断桌台信息
const check3TableInfo = function (req, res, next) {
    let params = getParams(req);
    if (params.store_id && params.table_id && params.num) {
        next()
    } else {
        res.redirect('/error?message=桌台信息错误')
    }
};

// 判断桌台信息
const check2TableInfo = function (req, res, next) {
    let params = getParams(req);

    if (params.store_id && params.table_id) {
        next()
    } else {
        res.redirect('/error?message=桌台信息错误')
    }
};

// 判断桌台信息
const check1TableInfo = function (req, res, next) {
    let params = getParams(req);
    if (params.store_id) {
        next()
    } else {
        res.redirect('/error?message=桌台信息错误')
    }
};


//判断是否有排队信息
const checkQueue = function (req, res) {
    let params = getParams(req);
    let userInfo = res.locals.userInfo;
    let token = res.locals.token;
    return new Promise((resolve, reject) => {
        axios.get(`/api/h5/customer/check-queue-order`, {
            params: {
                customer_id: userInfo.id,
                store_id: params.store_id,
                token
            }
        }).then(rs => {
            if (rs.data.error === 0) {
                resolve(rs);
            } else {
                res.redirect(`/error?message=${rs.data.desc}`)
            }
        }).catch(e => {
            reject(e)
        });
    })
};

/*
 * 默认跳转页面
 * */
router.get('/', function (req, res) {
    res.redirect('/error?message=请通过扫码进入')
});


/*
 * 扫描桌台首页
 * /tableIndex?store=1&table=12
 * */
router.get('/tableIndex', check2TableInfo, wxLogin, function (req, res, next) {
    checkQueue(req, res).then(rs => {
        let response = rs.data || {};
        let is_queue = response.data.is_queue; //0 表示无排队信息，1 表示有排队信息，但无预约菜品信息，2 表示有排队信息，也有预约菜品信息
        let order_id = response.data.order_id;
        let params = getParams(req);
        if (is_queue == 3) {
            res.redirect(`/dinner?store=${params.store_id}&table=${params.table_id}&order=${order_id}`);
        } else if (is_queue == 2) {
            res.redirect(`/confirm?store=${params.store_id}&table=${params.table_id}&num=${response.data.dining_count}&queue=${response.data.queue_id}&yuyue=y`)
        } else if (is_queue == 1) {
            res.redirect(`/menu?store=${params.store_id}&table=${params.table_id}&num=${response.data.dining_count}`)
        } else {
            next()
        }
    }).catch(e => {
        res.redirect('/error?message=请通过扫码进入')
    })
    // next()
});

/*
 * 选择人数
 * /select?store=1&table=12
 * */
router.get('/select', wxLogin, check2TableInfo);

/*
 * 菜单
 * /menu?store=1&table=12
 * */
router.get('/menu', wxLogin, check1TableInfo);

/*
 * 确认菜单
 * /confirm?store=1&table=12
 * */
router.get('/confirm', wxLogin, check2TableInfo);


/*
 * 扫描预约排队
 * /selectTable?store=1
 * */

router.get('/selectTable', wxLogin, check1TableInfo, function (req, res, next) {
    checkQueue(req, res).then(rs => {
        let response = rs.data.data || {};
        let is_queue = response.is_queue; //0 表示无排队信息，1 表示有排队信息，但无预约菜品信息，2 表示有排队信息，也有预约菜品信息
        let params = getParams(req);
        if (is_queue == 2 || is_queue == 1) {
            res.redirect(`/inNumber?store=${params.store_id}`)
        } else if (is_queue == 3) {
            let table_id = response.desk_id;
            let order_id = response.order_id;
            res.redirect(`/dinner?store=${params.store_id}&table=${table_id}&order=${order_id}`);
        } else {
            next()
        }
    }).catch(e => {
        res.redirect('/error?message=请通过扫码进入')
    });

});


/*
 * 取完号排号中
 * /inNumber?store=1
 * */

router.get('/inNumber', wxLogin, function (req, res, next) {
    checkQueue(req, res).then(rs => {
        let response = rs.data || {};
        let queue_id = response.data.queue_id;
        Object.assign(res.locals, {queueId: queue_id});
        next()
    }).catch(e => {
        res.redirect('/error?message=请通过扫码进入')
    });
});

/*
 * 用餐中
 * /dinner?store=1&table=1
 * */
router.get('/dinner', wxLogin, check2TableInfo);

/*
 *
 * /callServer?store=1&table=1
 * */
router.get('/callServer', wxLogin, check2TableInfo);

/*
 * 我的优惠券
 * /coupons?store=1
 * */
router.get('/coupons', wxLogin, check1TableInfo);

/*
 * 我的订单
 * /orderList?store=1
 * */
router.get('/orderList', wxLogin, check1TableInfo);

/*
 * 订单详情
 * /orderDetails?order=1
 * */
router.get('/orderDetails', wxLogin);


export default router